/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.startup.musicstore.services.crud.Impl;

import com.startup.musicstore.model.CreditCard;
import com.startup.musicstore.model.Customer;
import com.startup.musicstore.model.CustomerInvoice;
import com.startup.musicstore.model.Orders;
import com.startup.musicstore.services.crud.CustomerCreditCardService;
import com.startup.musicstore.services.crud.CustomerInvoiceCrudService;
import java.util.Date;
import java.util.List;
import org.joda.time.DateTime;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author given
 */
public class CustomerCreditCardServiceImpl implements CustomerCreditCardService{
    private static ApplicationContext ctx;    
        
    @Override
    public String getCustomerCreditCardResponse(Long customerInvoiceID, Long creditCardID) {
        ctx = new ClassPathXmlApplicationContext("classpath:com/startup/musicstore/app/conf/applicationContext-*.xml");
        CustomerInvoiceCrudService customerInvoiceCrudService = (CustomerInvoiceCrudService) ctx.getBean("customerInvoiceCrudService");
        List<CustomerInvoice> customerInvoices = customerInvoiceCrudService.findAll();
        for(CustomerInvoice ci: customerInvoices){
            if(customerInvoiceID.equals(ci.getId())){
                Orders order = ci.getOrder();
                Customer customer = order.getCustomer();
                List<CreditCard> creditCard = customer.getCreditCards();
                for(CreditCard cc: creditCard){
                    if(creditCardID.equals(cc.getId())){
                        if(cc.getExpiryDate().before(new DateTime().toDate()) && Double.parseDouble(cc.getBalance().toString()) > Double.parseDouble(ci.getOrderAmount().toString())){
                            ci.setInvoiceStatus("paid");
                            customerInvoiceCrudService.merge(ci);
                            return "paid";
                        }
                    }
                }
            }
        }
        return "unpaid";
    }
    
}
